package cn.felord.security.autoconfigure;

import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author felord.cn
 * @since 2021/4/6 16:43
 */
@AllArgsConstructor
public class JdbcRoleChecker implements RoleChecker {
    private final Function<Set<String>, Set<AntPathRequestMatcher>> function;


    @Override
    public boolean check(Authentication authentication, HttpServletRequest request) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.isEmpty()) {
            return false;
        }
        Set<String> roles = authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .map(role -> role.replace("ROLE_", ""))
                .collect(Collectors.toSet());
        Set<AntPathRequestMatcher> matchers = function.apply(roles);
        return matchers.stream()
                .anyMatch(matcher -> matcher.matches(request));
    }

    @Override
    public void afterPropertiesSet() {
        Assert.notNull(function, "function must not be null");

    }
}
